<template>
<div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
        <!-- 警告区域 -->
        <el-alert title="注意！只允许为第三级分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>
        <!-- 选择商品分类区域 -->
        <el-row class="cat_opts">
            <el-col :span="3">选择商品分类:</el-col>
            <!-- 商品分类的级联选择器 -->
            <el-col :span="21">
                <el-cascader v-model="selectedCateKeys" :options="cateList" :props="CateProps" @change="handleChange"></el-cascader>
            </el-col>
        </el-row>
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="动态参数" name="many">
                <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showAddDialog">添加参数</el-button>
                <!-- 动态参数表单 -->
                <el-table :data="manyTableData" border stripe>
                    <!-- 展开项 -->
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag :key="i" v-for="(item, i) in scope.row.attr_vals" closable :disable-transitions="false" @close="handleClose(i, scope.row)">
                                {{item}}
                            </el-tag>
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index">
                    </el-table-column>
                    <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteEditDialog(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
            <el-tab-pane label="静态属性" name="only">
                <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="showAddDialog">添加属性</el-button>
                <!-- 静态属性表单 -->
                <el-table :data="onlyTableData" border stripe>
                    <el-table-column type="expand">
                        <template slot-scope="scope">
                            <el-tag :key="i" v-for="(item, i) in scope.row.attr_vals" closable :disable-transitions="false" @close="handleClose(i, scope.row)">
                                {{item}}
                            </el-tag>
                            <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)"></el-input>
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column type="index">
                    </el-table-column>
                    <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="scope">
                            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteEditDialog(scope.row.attr_id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>

    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加' + TitleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRefs" label-width="90px">
            <el-form-item :label="TitleText" prop="attr_name">
                <el-input v-model="addForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog :title="'编辑' + TitleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRefs" label-width="90px">
            <el-form-item :label="TitleText" prop="attr_name">
                <el-input v-model="editForm.attr_name"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
    </el-dialog>

</div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 商品分类级联选择器选中的值
      selectedCateKeys: [],
      // 商品分类级联选择器的属性配置
      CateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
        // checkStrictly: true
      },
      // tab标签页默认选中的标签
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态参数数据
      onlyTableData: [],
      // 添加参数对话框显示与隐藏
      addDialogVisible: false,
      // 添加参数对话框表单数据
      addForm: {},
      // 添加参数对话框表单验证规则
      addFormRules: {
        attr_name: [{
          required: true,
          message: '请输入参数名称',
          trigger: 'blur'
        }]
      },
      // 编辑参数对话框显示与隐藏
      editDialogVisible: false,
      // 编辑参数对话框表单数据
      editForm: {
        attr_name: ''
      },
      // 编辑参数对话框表单验证规则
      editFormRules: {
        attr_name: [{
          required: true,
          message: '请输入参数名称',
          trigger: 'blur'
        }]
      }

    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类列表
    async getCateList() {
      const {
        data: res
      } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败！')
      }
      this.cateList = res.data
      // console.log(this.cateList);
    },
    // 监听商品分类级联选择器选中值的改变
    handleChange() {
      this.getParamData()
      // console.log(this.selectedCateKeys);
    },
    // 监听tab标签的变化
    handleClick() {
      // console.log(this.activeName);
      this.getParamData()
    },
    // 获取参数数据
    async getParamData() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // 获取参数列表
      const {
        data: res
      } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取参数列表失败！',
          type: 'error'
        })
      }

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })

      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 显示添加参数对话框
    showAddDialog() {
      this.addDialogVisible = true
    },
    // 添加参数对话框取消
    addDialogClosed() {
      this.$refs.addFormRefs.resetFields()
    },
    // 添加参数
    addParams() {
      this.$refs.addFormRefs.validate(async (valid) => {
        if (!valid) return this.$message.error('请输入正确格式！')
        const {
          data: res
        } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败！')

        this.$message.success('添加参数成功！')
        this.addDialogVisible = false
        this.getParamData()
      })
    },
    // 显示编辑参数对话框
    async showEditDialog(id) {
      const {
        data: res
      } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取编辑参数失败！')

      this.editForm = res.data
      // console.log(this.editForm);
      this.editDialogVisible = true
    },
    // 编辑参数对话框取消
    editDialogClosed() {
      this.$refs.editFormRefs.resetFields()
    },
    // 编辑参数
    async editParams() {
      const {
        data: res
      } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
        attr_name: this.editForm.attr_name,
        attr_sel: this.editForm.attr_sel,
        attr_vals: this.editForm.attr_vals
      })
      if (res.meta.status !== 200) return this.$message.error('编辑参数失败！')

      this.$message.success('编辑参数成功！')
      this.editDialogVisible = false
      this.getParamData()
    },
    // 删除参数
    async deleteEditDialog(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const {
        data: res
      } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除参数失败！')
      this.$message.success('删除参数成功！')
      this.getParamData()
    },
    // 显示添加标签的对话框
    showInput(row) {
      row.inputVisible = true
    },
    // 监听添加标签的对话框失去焦点或者按enter事件
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      this.saveAttrValue(row)
      row.inputVisible = false
    },
    handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrValue(row)
      row.inputVisible = false
    },
    // 编辑提交参数标签
    async saveAttrValue(row) {
      const {
        data: res
      } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('编辑参数标签失败！')
      this.$message.success('编辑参数标签成功！')
    }
  },
  computed: {
    isBtnDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },
    // 选择三级分类的id值
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 添加参数对话框标题内容
    TitleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }

  }
}
</script>

<style lang="less" scoped>
.cat_opts {
    margin: 15px;
    line-height: 40px;
}

.el-tag {
    margin: 15px;
}

.input-new-tag {
    width: 120px;
}
</style>
